package cn.com.xjnt.vas.web.ordering.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.frameworks.core.logger.annotation.RunLogger;
import com.frameworks.core.web.controller.BaseController;
import com.frameworks.core.web.page.WebPage;
import com.frameworks.core.web.result.DataResult;
import com.frameworks.core.web.result.MsgResult;
import com.frameworks.core.web.search.DynamicSpecifications;
import com.google.common.collect.Lists;

import cn.com.xjnt.vas.ordering.domain.entity.EmployeeInfo;
import cn.com.xjnt.vas.ordering.domain.entity.User;
import cn.com.xjnt.vas.ordering.domain.vo.EmployeeInfoVo;
import cn.com.xjnt.vas.ordering.service.EmployeeInfoService;
import cn.com.xjnt.vas.ordering.service.UserService;

/**
 * 类说明：
 * 
 * @author 作者 LUXIN
 * @version 创建时间：2016年5月10日18:16:52
 */
@Controller
@RequestMapping("/manage/ordering/employee")
public class EmployeeInfoController extends BaseController {

    private static final String VIEW_PAGE = "ordering/employee/view";
    private static final String FORM_PAGE = "ordering/employee/form";
    private static final String PHOTO_PAGE = "ordering/employee/photo";

    @Autowired
    private EmployeeInfoService employeeService;
    @Autowired
    private UserService userService;
    @Autowired
    private Mapper mapper;

    protected EmployeeInfoService getService() {
        return employeeService;
    }

    /**
     * view页面
     * 
     * @param request
     * @return
     */
    @RequiresPermissions(value = { "Order:employee:show" })
    @RequestMapping(value = "", method = { RequestMethod.GET })
    public ModelAndView show(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView(VIEW_PAGE);
        mav.addObject("organizationId", getLoginUser().getOrganization().getId());// 数据权限
        return mav;
    }

    /**
     * view页面list方法
     * 
     * @param request
     * @param webPage
     * @return
     */
    @RequiresPermissions(value = { "Order:employee:show" })
    @RequestMapping(value = "/list", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public DataResult list(HttpServletRequest request, WebPage webPage) {
        DataResult dataRet = new DataResult();
        try {
            Specification<EmployeeInfo> specification = DynamicSpecifications.bySearchFilter(request,
                    EmployeeInfo.class);
            List<EmployeeInfo> models = getService().findByCondition(specification, webPage);
            List<EmployeeInfoVo> lstVo = Lists.newArrayList();
            for (EmployeeInfo model : models) {
                EmployeeInfoVo vo = mapper.map(model, EmployeeInfoVo.class);
                lstVo.add(vo);
            }
            dataRet.pushOk("获取数据列表成功！");
            dataRet.setTotal(webPage.getTotalCount());
            dataRet.setRows(lstVo);
        } catch (Exception e) {
            dataRet.pushError("获取数据列表失败！");
            logger.error("获取数据列表异常！", e);
        }
        return dataRet;
    }

    /**
     * 新增
     * 
     * @param request
     * @return
     */
    @RequiresPermissions(value = { "Order:employee:show" })
    @RequestMapping(value = "/add", method = { RequestMethod.GET })
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView(FORM_PAGE);
        mav.addObject("organizationId", getLoginUser().getOrganization().getId());// 数据权限
        return mav;
    }

    /**
     * 修改
     * 
     * @param id
     * @return
     */
    @RequiresPermissions(value = { "Order:employee:show" })
    @RequestMapping(value = "/edit/{id}", method = { RequestMethod.GET })
    public ModelAndView edit(@PathVariable("id") Long id) {
        ModelAndView mav = new ModelAndView(FORM_PAGE);
        EmployeeInfo model = getService().findById(id);

        mav.addObject("employee", model);
        mav.addObject("organizationId", getLoginUser().getOrganization().getId());// 数据权限
        return mav;
    }

    /**
     * 预览照片
     * 
     * @param id
     * @return
     */
    @RequiresPermissions(value = { "Order:employee:show" })
    @RequestMapping(value = "/showImg/{id}", method = { RequestMethod.GET })
    public ModelAndView showImg(@PathVariable("id") Long id) {
        ModelAndView mav = new ModelAndView(PHOTO_PAGE);
        EmployeeInfo model = getService().findById(id);

        String fullName = model.getPhotoName();
        String extName = fullName.split("\\.")[1];

        String path = model.getPhotoImg();
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String base64Img = Base64Utils.encodeToString(data);
        String imgUrl = "";
        try {
            imgUrl = "data:image/" + extName + ";base64," + base64Img;
        } catch (Exception e) {
            e.printStackTrace();
        }
        mav.addObject("imgUrl", imgUrl);
        return mav;
    }

    /**
     * 保存
     * 
     * @param entity
     * @return
     */
    @RunLogger(value = "添加职工", isSaveRequest = true)
    @RequiresPermissions(value = { "Order:employee:add" })
    @RequestMapping(value = "/add", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult store(EmployeeInfo entity, @RequestParam(value = "photoImgFile") MultipartFile[] photoImg) {
        MsgResult msgRet = new MsgResult();
        try {
            User user = entity.getUser();
            // 检验手机号是否合法
            boolean b = userService.checkMobile(user, user.getMobile());
            if (!b) {
                msgRet.pushError("手机号已存在！请确认。");
                return msgRet;
            }

            getService().saveEmployeeInfo(entity, photoImg);
            msgRet.pushOk("添加成功！");
        } catch (Exception e) {
            msgRet.pushError("添加失败：" + e.getMessage());
            logger.error("添加时，发生异常！", e);
        }
        return msgRet;
    }

    /**
     * 更新
     * 
     * @param entity
     * @return
     */
    @RunLogger(value = "编辑职工", isSaveRequest = true)
    @RequiresPermissions(value = { "Order:employee:modify" })
    @RequestMapping(value = "/edit", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult modify(EmployeeInfo entity, @RequestParam(value = "photoImgFile") MultipartFile[] photoImg) {
        MsgResult msgRet = new MsgResult();
        try {
            User user = entity.getUser();
            // 检验手机号是否合法
            boolean b = userService.checkMobile(user, user.getMobile());
            if (!b) {
                msgRet.pushError("手机号已存在！请确认。");
                return msgRet;
            }
            entity.setRegTime(getService().findById(entity.getId()).getRegTime());

            getService().updateEmployeeInfo(entity, photoImg);
            msgRet.pushOk("修改成功!");
        } catch (Exception e) {
            msgRet.pushError("修改失败：" + e.getMessage());
            logger.error("修改时，发生异常！", e);
        }
        return msgRet;
    }

    /**
     * 删除
     * 
     * @param id
     * @return
     */
    @RunLogger(value = "删除职工", isSaveRequest = true)
    @RequiresPermissions(value = { "Order:employee:remove" })
    @RequestMapping(value = "/remove/{id}", method = { RequestMethod.POST }, produces = {
            MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult remove(@PathVariable("id") Long id) {
        MsgResult msgRet = new MsgResult();
        try {
            getService().deleteById(id);
            msgRet.pushOk("删除成功！");
        } catch (Exception e) {
            msgRet.pushError("删除失败：" + e.getMessage());
            logger.error("删除时，发生异常！", e);
        }
        return msgRet;
    }

    /**
     * 批量删除
     * 
     * @param ids
     * @return
     */
    @RunLogger(value = "批量删除职工", isSaveRequest = true)
    @RequiresPermissions(value = { "Order:employee:remove" })
    @RequestMapping(value = "/remove", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult remove(@RequestParam("ids[]") Long[] ids) {
        MsgResult msgRet = new MsgResult();
        try {
            getService().deleteByIds(ids);
            msgRet.pushOk("批量删除成功!");
        } catch (Exception e) {
            msgRet.pushError("批量删除失败：" + e.getMessage());
            logger.error("批量删除时，发生异常！", e);
        }
        return msgRet;
    }

    /**
     * 下载附件
     * 
     * @param id
     * @param res
     * @return
     */
    @RequestMapping(value = "/downloadImg", method = { RequestMethod.POST }, produces = {
            MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult downloadImg(Long id, HttpServletResponse res) {
        MsgResult msgRet = new MsgResult();
        try {
            EmployeeInfo model = getService().findById(id);
            String path = model.getPhotoImg();
            String name = model.getPhotoName();

            File file = new File(path);
            if (!file.exists()) {
                msgRet.pushError("文件不存在。");
                return msgRet;
            }
            InputStream ins = new FileInputStream(path);
            res.reset();
            res.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(name, "UTF-8"));
            res.setContentType("application/octet-stream; charset=utf-8");
            byte[] b = new byte[100];
            int len = 0;
            OutputStream os = res.getOutputStream();
            while ((len = ins.read(b)) > 0) {
                os.write(b, 0, len);
            }
            os.flush();
            ins.close();
            msgRet.pushOk("下载成功");
        } catch (Exception e) {
            msgRet.pushError("下载附件失败：" + e.getMessage());
            logger.error("下载附件时，发生异常！", e);
        }
        return msgRet;
    }

    /**
     * 删除附件
     * 
     * @param id
     * @param type
     * @return
     */
    @RequestMapping(value = "/deleteImg", method = { RequestMethod.POST }, produces = {
            MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult deleteImg(Long id) {
        MsgResult msgRet = new MsgResult();
        try {
            EmployeeInfo model = getService().findById(id);
            String path = model.getPhotoImg();

            File file = new File(path);
            if (!file.exists()) {
                logger.info("文件不存在");
            } else {// 文件存在
                getService().deleteImg(path);// 物理删除文件
            }

            msgRet.pushOk("文件删除成功");
            model.setPhotoImg("");
            model.setPhotoName("");
            model.setPhotoUrl("");
            getService().update(model);

        } catch (Exception e) {
            msgRet.pushError("删除附件失败：" + e.getMessage());
            logger.error("删除附件时，发生异常！", e);
        }
        return msgRet;
    }
}
